<?php

namespace App\Http\Controllers\Api;
use App\AdPosition;
use App\Attachment;
use App\SpecGoodsImage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class BaseController extends Controller
{
    protected $pageSize = 20;
    protected $orderBy = 'id';
    protected $orderType = 'desc';
    public function uploadVideo(Request $request)
    {
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            $file = $request->file('file');
            $fileSize = $file->getSize() / 1048576;
            if ($fileSize > 50) {
                return response(['message' => '允许上传最大视频为50M'],400);
            }
            $folder_name = "uploads/video/" . date("Ymd", time());
            $upload_path = storage_path() . '/app/public/' . $folder_name;
            $extension = $file->getClientOriginalExtension();
            $filename = time() . '_' . str_random(10) . '.' . $extension;
            // 将视频移动到我们的目标存储路径中
            $file->move($upload_path, $filename);
            return response(['path' => '/' . 'storage/' . $folder_name . '/' . $filename, 'message' => '上传成功']);
        }
        return response(['path' => '', 'message' => '未获取到上传文件或上传过程出错'],400);
    }

    public function uploadAudio(Request $request)
    {
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            $file = $request->file('file');
            $fileSize = $file->getSize() / 1048576;
            if ($fileSize > 10) {
                return response(['message' => '允许上传最大音频文件为10M'],400);
            }
            $folder_name = "uploads/audio/" . date("Ymd", time());
            $upload_path = storage_path() . '/app/public/' . $folder_name;
            $extension = $file->getClientOriginalExtension();
            $filename = time() . '_' . str_random(10) . '.' . $extension;
            // 将视频移动到我们的目标存储路径中
            $file->move($upload_path, $filename);
            return response(['path' => '/' . 'storage/' . $folder_name . '/' . $filename, 'message' => '上传成功']);
        }
        return response(['message' => '未获取到上传文件或上传过程出错'],400);
    }

    public function uploadFile(Request $request)
    {
        if (!$request->file('file')) {
            return response(['message' => '文件数据异常'], 400);
        }
        $file = $request->file('file');
        $ext = strtolower($file->getClientOriginalExtension());
        $folder = $request->get('folder') ? $request->get('folder') : 'files';
        $path = $folder.'/'.date('Ym');
        $filename = md5(time().str_random(10)).'.'.$ext;
        $rs = Storage::disk('public')->putFileAs($path, $file, $filename, 'public');
        if ($rs) {
            return response($path . '/' . $filename);
        }
        return response(['message' => '上传失败', 400]);
    }
    public function uploadAttachment(Request $request)
    {
        if (!$request->file('file') || !$request->attachmentable_type) {
            return response(['message' => '文件数据异常'], 400);
        }
        $file = $request->file('file');
        $ext = strtolower($file->getClientOriginalExtension());
        $oName = $file->getClientOriginalName();
        $mimeType = $file->getClientMimeType();
        $path = 'attachments/'.date('Ym');
        //是图片则进行处理
        if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])) {
            $path = $path.'/'.md5(time().str_random(20)).'.'.$ext;
            $image = Image::make($file)->orientate();
            if ($request->get('width') && $request->get('height')) {
                $image->fit($request->width, $request->height);
            }
            $image->encode();
            Storage::disk('public')->put($path, (string)$image, 'public');
        } else {
            $path = $file->store($path, 'public');
        }
        if ($path) {
            $attachment = Attachment::create([
                'attachmentable_id' => $request->get('attachmentable_id'),
                'attachmentable_type' => $request->get('attachmentable_type'),
                'name' => $oName,
                'url' => $path,
                'mime_type' => $mimeType,
                'ext' => $ext
            ]);
            return response($attachment);
        }
        return response(['message' => '上传失败', 400]);
    }

    /**
     * 上传商品规格图片
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function uploadSpecGoodsImage(Request $request)
    {
        if (!$request->file('file')) {
            return response(['message' => '文件数据异常'], 400);
        }
        $file = $request->file('file');
        $ext = strtolower($file->getClientOriginalExtension());
        $path = 'specs/'.date('Ym');
        //是图片则进行处理
        $path = $path.'/'.md5(time().str_random(20)).'.'.$ext;
        $image = Image::make($file)->orientate();
        if ($request->get('width') && $request->get('height')) {
            $image->fit($request->width, $request->height);
        }
        $image->encode($ext, 80);
        Storage::disk('public')->put($path, (string)$image, 'public');
        $specImage = SpecGoodsImage::create([
            'goods_id' => $request->goods_id,
            'thumb' => $path,
            'spec_item_id' => $request->spec_item_id,
        ]);
        return response($specImage);
    }

    /**
     * 编辑器图片上传
     *
     * @param Request $request
     * @return null|string
     */
    public function uploadEditorImage(Request $request) {
        $file = $request->file('file');
        $ext = $file->getClientOriginalExtension();
        $path = 'images/editor/'.date('Ym/').md5(time().str_random(20)).'.'.$ext;
        $image = Image::make($file)->orientate()->encode($ext, 80);
        if (Storage::disk('public')->put($path, (string)$image, 'public')) {
            return asset('storage/'.$path);
        }
        return null;
    }

    public function uploadImage(Request $request) {
        $file = $request->file('file');
        $folder = $request->get('folder') ? $request->get('folder') : 'thumb';
        $ext = $file->getClientOriginalExtension();
        $path = 'images/' . $folder . '/'.date('Ym/').md5(time().str_random(20));
        $originalPath = $path.'.'.$ext;
        $thumbPath = $path.'_thumb.'.$ext;
        $image = Image::make($file);
        $image->orientate();
        $image->encode();
        Storage::disk('public')->put($originalPath, (string)$image, 'public');
        if ($request->get('width') && $request->get('height')) {
            $image->fit($request->width, $request->height);
        }
        $image->encode();
        Storage::disk('public')->put($thumbPath, (string)$image, 'public');
        return response([
            'original_img' => $originalPath,
            'thumb_img' => $thumbPath
        ]);
    }

    public function uploadThumbImage(Request $request) {
        $file = $request->file('file');
        $folder = $request->get('folder') ? $request->get('folder') : 'thumb';
        $ext = $file->getClientOriginalExtension();
        $path = 'images/' . $folder . '/'.date('Ym/').md5(time().str_random(20));
        $thumbPath = $path.'.'.$ext;
        $image = Image::make($file);
        $image->orientate();
        if ($request->get('width') && $request->get('height')) {
            $image->fit($request->width, $request->height);
        }
        $image->encode();
        Storage::disk('public')->put($thumbPath, (string)$image, 'public');
        return $thumbPath;
    }

    public function uploadAdImage(Request $request) {
        $file = $request->file('file');
        $folder = $request->get('folder') ? $request->get('folder') : 'thumb';
        $ext = $file->getClientOriginalExtension();
        $path = 'images/' . $folder . '/'.date('Ym/').md5(time().str_random(20));
        $thumbPath = $path.'.'.$ext;
        $image = Image::make($file);
        $image->orientate();
        if ($request->get('position_id')) {
            $position = AdPosition::find($request->get('position_id'));
            $image->fit($position->width, $position->height);
        }
        $image->encode();
        Storage::disk('public')->put($thumbPath, (string)$image, 'public');
        return $thumbPath;
    }
    /**
     * @param $arr
     * @param $m
     * @param int $isRepeat
     * @param array $b
     * @param int $n
     * @param array $res
     * @return array
     * 获取字符串的所有组合方式
     */
    public function combine($arr, $m, $isRepeat = 0, $b = [], $n = 0, $res = []) {
        !$n && $n = $m;

        if($m == 1) {
            foreach($arr as $item)
                $res[] = array_merge($b, [$item]);
        } else {
            foreach($arr as $key => $item) {
                $b[$n - $m] = $item;

                $tmp = $arr;
                if(!$isRepeat) unset($tmp[$key]);

                $res = self::combine($tmp, $m-1, $isRepeat, $b, $n, $res);
            }
        }

        return $res;
    }
}
